package cn.daniellee.plugin.wc.listener;

import cn.daniellee.plugin.wc.WorldChecker;
import cn.daniellee.plugin.wc.model.Confirm;
import cn.daniellee.plugin.wc.model.WorldNeedCheck;
import net.md_5.bungee.api.ChatColor;
import net.md_5.bungee.api.chat.ClickEvent;
import net.md_5.bungee.api.chat.ComponentBuilder;
import net.md_5.bungee.api.chat.HoverEvent;
import net.md_5.bungee.api.chat.TextComponent;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerTeleportEvent;

public class PlayerListener implements Listener {

	@EventHandler
	public void onPlayerTeleport(PlayerTeleportEvent e) {
		// 如果传送前后的世界相同则不进行处理
		if (e.getFrom().getWorld() == e.getTo().getWorld()) return;
		// 否则进行判断
		Player player = e.getPlayer();
		WorldNeedCheck worldNeedCheck = WorldChecker.getInstance().getWorldNeedCheckByWorldName(e.getTo().getWorld().getName());
		// 如果进入的是受限的世界
		if (worldNeedCheck != null) {
			// 如果没有权限进入
			if (!player.hasPermission(worldNeedCheck.getPermission())) {
				e.setCancelled(true);
				// 如果允许付费进入
				if (worldNeedCheck.isAllowPaid()) {
					// 检查是否已确认
					Confirm confirm = WorldChecker.getInstance().getConfirmMap().get(player.getName());
					if (confirm != null && confirm.isConfirm()) {
						WorldChecker.getInstance().getConfirmMap().remove(player.getName());
						e.setCancelled(false);
					} else {
						WorldChecker.getInstance().getConfirmMap().put(player.getName(), new Confirm(e.getTo(), worldNeedCheck.getCostType(), worldNeedCheck.getCostPerJoin()));
						// 发送确认信息
						String message = WorldChecker.getInstance().getConfig().getString("message.confirm-pay", "&eClick to confirm teleport and pay &b{cost} &e{type}.").replace("{cost}", Double.toString(worldNeedCheck.getCostPerJoin())).replace("{type}", WorldChecker.getInstance().getConfig().getString("message.type." + worldNeedCheck.getCostType(), worldNeedCheck.getCostType()));
						TextComponent confirmText = new TextComponent((WorldChecker.getInstance().getPrefix() + message).replace("&", "§"));
						confirmText.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/worldchecker confirm"));
						confirmText.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new ComponentBuilder(message.replace("&", "§")).color(ChatColor.BLUE).create()));
						player.spigot().sendMessage(confirmText);
					}
				// 否则取消传送
				} else {
					player.sendMessage((WorldChecker.getInstance().getPrefix() + WorldChecker.getInstance().getConfig().getString("message.cant-teleport", "&eYou do not have access to this world.")).replace("&", "§"));
				}
			}
		}
	}

}
